package com.ecube.maintenance.components.fragment;

import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.ecube.maintenance.R;
import com.ecube.maintenance.biz.apis.impl.UserAction;
import com.ecube.maintenance.biz.commons.Constants;
import com.ecube.maintenance.biz.commons.ICCallBack;
import com.ecube.maintenance.biz.commons.ICTException;
import com.ecube.maintenance.components.dialog.CustomProgressDialog;
import com.ecube.maintenance.pojos.UserInfo;
import com.ecube.maintenance.utils.Bog;
import com.ecube.maintenance.utils.StringUtil;
import com.google.gson.internal.StringMap;

public class LoginFragment extends Fragment {
    int timeCounter = 0;
    /**
     * reset CAPTCHA button per sixty seconds.
     */
    boolean isCoolingDown = false;
    /**
     * runnable
     */
    Runnable mRunnable;
    Handler mHandler;
    private CustomProgressDialog mProgressDialog;
    /**
     * text view with user's cellphone number.
     */
    private TextView mPhoneNumber;
    /**
     * text view with CAPTCHA.
     */
    private TextView mCAPTCHA;
    /**
     * button will send a request to server to get information .
     */
    private Button mCAPTCHAbutton;

    /**
     * construct method with no parameter.
     */
    public LoginFragment() {
    }

    /**
     * this method will return a new instance of this fragment.Will be called fragment transaction.
     *
     * @return
     */
    public static LoginFragment newInstance() {
        LoginFragment fragment = new LoginFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    /**
     * onCreate method.
     *
     * @param savedInstanceState if this is not null,fragment will recover data into its content view.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.mProgressDialog = CustomProgressDialog.createDialog(getActivity()).setMessage("请稍候...");
        mProgressDialog.setCancelable(false);

        if (getArguments() != null) {
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_login, container, false);
        mPhoneNumber = (EditText) rootView.findViewById(R.id.phone);
        mCAPTCHA = (EditText) rootView.findViewById(R.id.CAPTCHA);
        mCAPTCHAbutton = (Button) rootView.findViewById(R.id.btn_get_code);
        mCAPTCHAbutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String number = mPhoneNumber.getText().toString();
                if (!StringUtil.isValidPhoneNumber(number)) {
                    Bog.toast("请正确输入手机号.");
                    return;
                }
                if (!v.isEnabled()) return;
                mProgressDialog.show();
                timeCounter = 60;
                UserAction.fetchValidCodes(mPhoneNumber.getText().toString(), new ICCallBack() {

                    @Override
                    public void done(Object result, ICTException exception) {
                        mProgressDialog.dismiss();
                        if (exception != null) {
                            Bog.toast("获取验证码异常，请重试.");
                            timeCounter = 0;
                            return;
                        }
                        Bog.toast("验证码已发送.");
                        if (Constants.DEBUG_MODE) {
                            try {
                                Double k = ((StringMap<Double>) result).get("key");
                                String key = k.intValue() + "";
                                Bog.toast(key);
                            } catch (Exception e) {
                                if (result != null)
                                    Bog.e(result.toString());
                            }
                        }

                    }
                });
            }
        });
        rootView.findViewById(R.id.btn_login).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                mProgressDialog.show();
                UserAction.logins(mPhoneNumber.getText().toString(),
                        mCAPTCHA.getText().toString(),
                        new ICCallBack<UserInfo>() {
                            @Override
                            public void done(UserInfo result, ICTException exception) {
                                mProgressDialog.dismiss();
                                if (exception != null) {
                                    if (exception.getMessageCode() == ICTException.E_APP_USERPWDERROR) {
                                        Bog.toast(getString(R.string.valid_code_error));
                                    }
                                    Bog.e( exception.getMessage());
                                } else {
                                    Bog.toast(getString(R.string.login_success));
                                    getFragmentManager().popBackStack();
                                }

                            }
                        });
            }
        });
        initView();
        return rootView;
    }

    private void initView() {
        mHandler = new Handler();
        mRunnable = new Runnable() {
            @Override
            public void run() {
                if (timeCounter == 60 && !isCoolingDown) {
                    mCAPTCHAbutton.setTextColor(getResources().getColor(R.color.ict_theme_red));
                    isCoolingDown = true;
                    mCAPTCHAbutton.setEnabled(false);
                } else if (timeCounter == 0 && isCoolingDown) {
                    mCAPTCHAbutton.setTextColor(getResources().getColor(R.color.ict_text_dark));
                    mCAPTCHAbutton.setText(getString(R.string.fetch_valid_code));
                    mCAPTCHAbutton.setEnabled(true);
                    isCoolingDown = false;
                }
                if (timeCounter != 0) {
                    mCAPTCHAbutton.setText(
                            new StringBuilder()
                            .append(timeCounter)
                                    .append(getString(R.string.fetch_valid_code_again)).toString());
                }
                mHandler.postDelayed(mRunnable, 1000);
                if (timeCounter > 0) timeCounter--;
            }
        };
        mHandler.post(mRunnable);

    }

    @Override
    public void onResume() {
        super.onResume();
        configureActionBar();
    }

    private void configureActionBar() {
        ActionBar actionBar = getActivity().getActionBar();
        assert actionBar != null;
        View v = actionBar.getCustomView();
        if (v != null) {
            v.setVisibility(View.GONE);
        }
        actionBar.setDisplayShowTitleEnabled(true);
        actionBar.setTitle("登录");

    }


    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mHandler.removeCallbacks(mRunnable);
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    public void onPrepareOptionsMenu(Menu menu) {
        menu.clear();
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
    }

}
